package com.yida.common.core.utils;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import cn.hutool.json.JSONUtil;
import com.yida.common.core.vo.SecretKeyVO;
import com.yida.common.core.web.domain.AjaxResult;
import org.bouncycastle.jcajce.provider.asymmetric.ec.GMCipherSpi;

import java.util.Base64;

/**
 * @Description 加密工具类
 * @Author wws
 * @Date 2023-03-24
 */
public class EncryptUtil {

    /**
     * 获取国密公钥私钥
	 * @return
	 */

	public static SecretKeyVO getSecretKey(){
		// 国密SM2加密方法
		SM2 sm2 = SmUtil.sm2();
		SecretKeyVO secretKeyVO = new SecretKeyVO();
		secretKeyVO.setPublicKey(sm2.getPublicKeyBase64());
		secretKeyVO.setPrivateKey(sm2.getPrivateKeyBase64());
		return secretKeyVO;
	}

	/**
	 * 国密加密
	 * @param publicKey 公钥
	 * @param privateKey 私钥
	 * @param plaintext 铭文
	 * @return
	 */
	public static String encrypt(String publicKey, String privateKey, String plaintext) {
		SM2 sm2 = SmUtil.sm2(privateKey, publicKey);
		return sm2.encryptBase64(plaintext, KeyType.PublicKey);
	}

	/**
	 * 国密解密
	 * @param publicKey 公钥
	 * @param privateKey 密钥
	 * @param ciphertext 密文
	 * @return
	 */
	public static String decrypt(String publicKey, String privateKey, String ciphertext) {
		SM2 sm2 = SmUtil.sm2(privateKey, publicKey);
		return sm2.decryptStr(ciphertext, KeyType.PrivateKey);
	}

}
